<template>
    <el-container class="app-container" v-loading="loading">
        <el-header style="height: auto;border: 1px solid #cccccc;padding:25px 25px 5px 25px;">
            <el-form ref="form" :model="queryform" :inline="true" label-width="80px"
                     class="search-form-inline" size="mini">
                <el-form-item label="" style="width:120px;">
                    <el-input v-model="queryform.rackNumber" placeholder="请输入机柜编号"/>
                </el-form-item>
                <el-form-item label="" style="width:120px;">
                    <el-input v-model="queryform.assetNumber" placeholder="请输入资产编号"/>
                </el-form-item>
                <el-form-item label="" style="width:120px;">
                    <el-input v-model="queryform.ip" placeholder="请输入IP"/>
                </el-form-item>
                <el-form-item label="" style="width:120px;">
                    <el-input v-model="queryform.responsible" placeholder="请输入负责人"/>
                </el-form-item>
                <el-form-item label="" style="width:80px;">
                    <el-select v-model="queryform.status" placeholder="状态">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="开机" value="0"></el-option>
                        <el-option label="关机" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="" style="width:120px;">
                    <el-select v-model="queryform.runTime" placeholder="运行时间">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="9H" value="9"></el-option>
                        <el-option label="24H" value="24"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上架时间">
                    <CuDatepicker @update-date="updatePutDate" :def="false" :format="'yyyy-MM-dd'" size="mini"
                                  :uiType="'daterange'" style="width: 300px;"/>
                </el-form-item>
                <el-form-item label="下架时间">
                    <CuDatepicker @update-date="updateOffDate" :def="false" :format="'yyyy-MM-dd'" size="mini"
                                  :uiType="'daterange'" style="width: 300px;"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handlequery">查 询</el-button>
                </el-form-item>
            </el-form>
        </el-header>
        <el-main>
            <el-container>
                <el-header style="height: auto;padding: 10px 0 5px 30px;">
                    <el-button type="primary" @click="add" size="mini">新 增</el-button>
                    <!--<el-button type="danger" @click="batchDel" size="mini">删 除{{multipleSelection.length!==0?'选中'+multipleSelection.length+'记录':''}}</el-button>-->
                    <!--<el-button @click="importExcel" size="mini">导 入</el-button>-->
                    <el-button @click="exportExcel" size="mini">导
                        出{{multipleSelection.length!==0?'选中'+multipleSelection.length+'记录':''}}
                    </el-button>

                    <div style="float: right;">
                        <!--<el-button type="success" size="mini" @click="powerOn">批量开机</el-button>-->
                        <!--<el-button type="info"  size="mini" @click="shutDown">批量关机</el-button>-->
                    </div>

                </el-header>
                <el-main>
                    <DynamicTable
                            :columns="tableColumns"
                            :list="tableData" :current-page="currentPage"
                            ref="singleTable"
                            @selection-change="handleSelectionChange"
                    >
                        <template slot="top">
                            <el-table-column type="selection" width="55"></el-table-column>
                        </template>
                        <template slot="end">
                            <el-table-column label="状态" align="center" :fixed="fixed">
                                <template slot-scope="scope">
                                    <span class="status" style='color:#67C23A;' v-if="scope.row.state === 0 ">开机</span>
                                    <span class="status" style='color:red;' v-else>关机</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center" :min-width="200" :fixed="fixed">
                                <template slot-scope="scope">
                                    <el-row>
                                        <el-button @click="handleOn(scope.row)" type="text" size="small" v-if="scope.row.machineType==='服务器'">开机
                                        </el-button>
                                        <el-button @click="handleDown(scope.row)" type="text" size="small" v-if="scope.row.machineType==='服务器'">关机
                                        </el-button>
                                        <el-button @click="handleEdit(scope.row)" type="text" size="small">修改
                                        </el-button>
                                        <el-button @click="handleUserPwd(scope.row)" type="text" size="small"
                                                   v-if="scope.row.pwIsExist">修改账号密码
                                        </el-button>
                                        <el-button @click="handleDelete(scope.row)" type="text" size="small">下架
                                        </el-button>
                                    </el-row>
                                </template>
                            </el-table-column>
                        </template>
                    </DynamicTable>
                </el-main>
            </el-container>
        </el-main>
        <el-footer style="height: auto;">
            <CustomPage
                    :currentPage="currentPage"
                    :pageSize="pageSize"
                    :total="total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
            />
        </el-footer>
        <UploadDialog ref="upload" :uploadUrl="uploadUrl" @uploaded="()=>{loadData()}"></UploadDialog>

        <el-dialog
                :title="centerDialogTitle"
                :visible.sync="centerDialogVisible"
                :close-on-click-modal="false"
                :append-to-body="true"
                width="30%"
                center>

            <el-form :model="deviceForm" :rules="userRules" ref="deviceForm" label-width="100px" size="medium"
                     :key="centerDialogVisible" v-loading="dialogloading">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="用户名" prop="osUser">
                            <el-input v-model="deviceForm.osUser" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20">
                        <el-form-item label="密码" prop="osPass">
                            <el-input
                                    type="password"
                                    auto-complete="off"
                                    v-model.trim="deviceForm.osPass"
                                    placeholder="请输入新密码"
                                    onpaste="return false"
                                    onselectstart="return false"
                                    v-filterSpecialChar
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="保存账号密码">
                            <el-switch v-model="deviceForm.isSave"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogDown">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog
                title="修改账号密码"
                :visible.sync="userDialogVisible"
                :close-on-click-modal="false"
                :append-to-body="true"
                width="30%"
                v-loading="dialogloading"
                center>

            <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="100px" size="medium"
                     :key="userDialogVisible">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="用户名" prop="osUser">
                            <el-input v-model="userForm.osUser" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20">
                        <el-form-item label="原密码" prop="originalPassword">
                            <el-input
                                    type="password"
                                    auto-complete="off"
                                    v-model.trim="userForm.originalPassword"
                                    placeholder="请输入原密码"
                                    onpaste="return false"
                                    onselectstart="return false"
                                    v-filterSpecialChar
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="新密码:" prop="osPass">
                            <el-input
                                    type="password"
                                    auto-complete="off"
                                    v-model.trim="userForm.osPass"
                                    placeholder="请输入密码"
                                    onpaste="return false"
                                    onselectstart="return false"
                                    v-filterSpecialChar></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="userDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="userDialogSave">确 定</el-button>
            </span>
        </el-dialog>

    </el-container>
</template>

<script>
import CustomPage from '@/common/CustomPage';
import CuDatepicker from '@/common/CuDatepicker';
import DynamicTable from '@/common/DynamicTable';
import UploadDialog from '@/common/UploadDialog';

export default {
  components: {
    CustomPage, CuDatepicker, DynamicTable, UploadDialog
  },
  data() {
    return {
      loading: false,
      dialogloading: false,
      centerDialogVisible: false,
      userDialogVisible: false,
      centerDialogTitle: '',
      fixed: 'right',
      deviceForm: {
        osUser: '',
        osPass: '',
        isSave: false
      },
      userForm: {
        id: '',
        originalPassword: '',
        osUser: '',
        osPass: ''
      },
      userRules: {
        osUser: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        osPass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        originalPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value) {
                this.$axiosInstance({
                  method: 'get',
                  url: '/changeMachinePw',
                  params: {
                    id: this.userForm.id,
                    originalPassword: this.userForm.originalPassword
                  }
                })
                  .then(result => {
                    if (result.data.code === 200) {
                      callback();
                    } else {
                      callback(new Error('原密码错误'));
                    }

                  })
                  .catch(() => {
                    callback(new Error('原密码错误'));
                  });
              }
            },
            trigger: 'blur',
          },
        ],
      },
      shutDownForm: {},
      queryform: {
        rackNumber: null,
        assetNumber: null,
        runTime: '',
        ip: '',
        status: '',
        shelfTimeStart: null,
        shelfTimeEnd: null,
        underTimeStart: null,
        underTimeEnd: null,
      },
      uploadUrl: '',
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      tableColumns: [
        {
          field: 'rackNumber',
          title: '机柜编号',
          width: '80px',
        },
        {
          field: 'assetNumber',
          title: '资产编号',
          width: '80px',
        },
        {
          field: 'ip',
          title: '设备IP',
          width: '140px',
        },
        {
          field: 'mac',
          title: 'MAC地址',
          width: '140px',
        },
        {
          field: 'machineType',
          title: '设备类型',
          width: '100px',
        },
        {
          field: 'height',
          title: '设备高度',
          width: '100px',
        },
        {
          field: 'rackDept',
          title: '所属部门',
          width: '100px',
        },
        {
          field: 'responsible',
          title: '负责人',
          width: '100px',
        },
        {
          field: 'usage',
          title: '设备用途',
        },
        {
          field: 'runTime',
          title: '运行时间',
          width: '100px',
          renderer: (v) => {
            let str = '';
            switch (v.runTime) {
            case 9:
              str = '9H';
              break;
            case 12:
              str = '12H';
              break;
            case 24:
              str = '永不关机';
              break;
            case -1:
              str = String('0'.repeat(2) + v.startOnTime).slice(-2) + ':00' + '-' + String('0'.repeat(2) + v.shutdownTime).slice(-2) + ':00';
              break;
            }

            return str
          }
        },
        {
          field: 'putaway',
          title: '上架时间',
          width: '120px',
          renderer: (v) => {
            return v.putaway ? new Date(v.putaway).format('yyyy-MM-dd') : '-'
          }
        },
        {
          field: 'removeTime',
          title: '下架时间',
          width: '120px',
          renderer: (v) => {
            return v.removeTime ? new Date(v.removeTime).format('yyyy-MM-dd') : '-'
          }
        },
        {
          field: 'fld_param',
          title: '备注',
        },
      ],
    }
  },
  watch: {
    centerDialogVisible: {
      handler(val, o) {
        if (!val) this.shutDownForm = {}
      },
      immediate: true,
      deep: true
    },
    userDialogVisible: {
      handler(val, o) {
        if (!val) this.userForm = {
          id: '',
          originalPassword: '',
          osUser: '',
          osPass: ''
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.loadData()
    this.$nextTick(() => {
      let pw = this.$refs['singleTable'].$el.getBoundingClientRect().width;
      let tw = this.$refs['singleTable'].$el.querySelector('.el-table__body').getBoundingClientRect().width;

      if (tw > pw) {
        this.fixed = 'right';
      }
    })
  },
  methods: {
    handleUserPwd(row) {
      this.userForm.id = row.id;
      this.userDialogVisible = true;
    },
    userDialogSave() {
      this.$refs['userForm'].validate((v) => {
        if (!v) return;
        this.dialogloading = true;
        this.$axiosInstance({
          method: 'get',
          url: '/changeMachinePw',
          params: {
            ...this.userForm
          }
        }).then((result) => {
          if (result.data.code === 200) {
            this.$message({
              message: result.data.message,
              type: 'success'
            });
            this.userDialogVisible = false;
            this.loadData();
          } else {
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }

          this.dialogloading = false;
        }).catch((err) => {
          this.dialogloading = false;
        })
      });

    },
    updatePutDate(v) {
      this.queryform.shelfTimeStart = v[0];
      this.queryform.shelfTimeEnd = v[1];
    },
    updateOffDate(v) {
      this.queryform.underTimeStart = v[0];
      this.queryform.underTimeEnd = v[1];
    },
    handleOn(row) {

      this.$confirm('确定要开机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // this.centerDialogTitle='开机';
        // this.centerDialogVisible=true;
        this.switchMachine(row);
      })
    },
    dialogDown() {
      this.$refs['deviceForm'].validate((v) => {
        if (!v) return
        this.dialogloading = true;
        this.offMachine(this.shutDownForm, () => {
          this.dialogloading = false;
        });
      });
    },
    handleDown(row) {
      this.$confirm('确定要关机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        if (!row.pwIsExist) {
          this.centerDialogTitle = '关机';
          this.centerDialogVisible = true;
          this.shutDownForm = row;
        } else {
          this.offMachine(row);
        }
      })
    },
    offMachine(row, call) {
      this.loading = true;
      this.$axiosInstance({
        method: 'get',
        url: '/offMachine',
        params: {
          id: row.id,
          ...this.deviceForm
        }
      })
        .then(result => {
          if (result.data.code === 200) {
            this.$message({
              message: result.data.message,
              type: 'success'
            });
            this.loadData();
          } else {
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }
          this.loadData();
          this.loading = false;
          if (call) call();
        })
        .catch(() => {
          this.loading = false;
          if (call) call();
        });
    },
    switchMachine(row, call) {
      this.loading = true;
      this.$axiosInstance({
        method: 'get',
        url: '/onMachine',
        params: {
          id: row.id
        }
      })
        .then(result => {
          if (result.data.code === 200) {
            this.$message({
              message: result.data.message,
              type: 'success'
            });
            this.loadData();
          } else {
            this.$message({
              message: result.data.message,
              type: 'error'
            });
          }
          this.loadData();
          this.loading = false;
          if (call) call();
        })
        .catch(() => {
          this.loading = false;
          if (call) call();
        });
    },
    powerOn() {
      this.$confirm('确定要全部开机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.loadData();
      })
    },
    shutDown() {
      this.$confirm('确定要全部关机？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.loadData();
      })
    },
    handleEdit(row) {
      this.$store.dispatch('setActiveMenuAsyn', ['editordevice']);
      this.$emit('changeComponent', {
        active: 'add',
        handleType: 'editor',
        ...row
      });
    },
    add() {
      this.$store.dispatch('setActiveMenuAsyn', ['adddevice']);
      this.$emit('changeComponent', {
        active: 'add',
        handleType: 'add'
      });
    },
    batchDel() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning({
          showClose: true,
          message: '至少选择一条数据！',
        });
      }
      this.loading = true;
      let promise = [];
      this.multipleSelection.forEach(d => {
        let id = d;
        let p = new Promise((resolve, reject) => {

          this.$axiosInstance({
            method: 'get',
            url: '/delMachine',
            params: {
              id
            }
          })
            .then(result => {
              if (result.data.code === 200) {
                resolve();
              } else {
                this.$message({
                  message: result.data.message,
                  type: 'error'
                });
                reject();
              }
            })
            .catch(() => {
            });
        });
        promise.push(p);
      });
      Promise.all(promise).then(() => {
        console.log('全部执行完毕');
        this.loadData();
      }).catch(() => {
        this.loading = false;
      })


    },
    importExcel() {
      this.$refs['upload'].show();
    },
    exportExcel() {

      var html = '';
      let url = APIObj.apiUrl + '/export';
      // let url = 'http://127.0.0.1:8080/api/export';

      var form = document.createElement('form');
      form.setAttribute('method', 'get');
      form.setAttribute('action', url);

      var $form = $(form);

      for (let k in this.queryform) {
        if (this.queryform[k]) {
          html += '<input type=\'hidden\' name="' + k + '" value=\'' + this.queryform[k] + '\'/>';
        }

      }
      this.multipleSelection.forEach(item => {
        html += '<input type=\'hidden\' name="ids" value=\'' + item + '\'/>';
      });

      $form.append(html).appendTo('body');
      form.submit();
      $(form).remove();

    },
    handleDelete(item) {
      this.$confirm('确定要下架吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$axiosInstance({
          method: 'get',
          url: '/downMachine',
          params: {
            id: item.id
          }
        })
          .then(result => {
            if (result.data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
              });
              this.loadData();
            } else {
              this.$message({
                message: '操作失败',
                type: 'error'
              });
            }
            this.loadData();
          })
          .catch(() => {
          });
      })

    },
    loadData() {
      this.loading = true;
      this.$axiosInstance({
        method: 'get',
        url: '/getMachineDetail.json',
        params: {
          pageNum: (this.currentPage - 1),
          pageSize: this.pageSize,
          ...this.queryform
        }
      }).then((res) => {
        let { code, data } = res.data;
        if (code === 200) {
          this.tableData = data.content;
          this.total = data.total;
          if (data.content.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.loadData();
          }
        } else {
          this.tableData = [];
          this.total = 0;
        }
        this.loading = false;
      }).catch((err) => {
        this.loading = false;
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handlequery() {
      this.currentPage = 1;
      this.loadData()
    },
    handleSizeChange(size) {
      this.currentPage = 1;
      this.pageSize = size;
      this.loadData()
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadData()
    },
  }
}
</script>

<style lang="less" scoped>
    .status {
        cursor: pointer;
    }
</style>
